from rest_framework import serializers
from .models import *


class CommentLikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CommentLike
        fields = '__all__'

    def to_representation(self, instance):
        print("Serializing CommentLike instance:", instance)
        return super().to_representation(instance)


class CommentSerializer(serializers.ModelSerializer):
    is_like = CommentLikeSerializer(many=True, read_only=True, source='comment_likes')
    student_name = serializers.CharField(source='student.name', read_only=True)
    parent = serializers.PrimaryKeyRelatedField(queryset=Comment.objects.all(), allow_null=True, required=False)
    student = serializers.PrimaryKeyRelatedField(queryset=Student.objects.all())
    post = serializers.PrimaryKeyRelatedField(queryset=Post.objects.all())
    nickname = serializers.CharField(source='student.nickname', read_only=True)
    avatar = serializers.CharField(source='student.image', read_only=True)

    class Meta:
        model = Comment
        fields = '__all__'

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # print("Instance:", instance)
        # print("Comment Likes:", instance.comment_likes.all())
        if 'is_like' not in representation:
            representation['is_like'] = []
        return representation


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'


class PostLikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostLike
        fields = ['student']


class PostImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostImage
        fields = ['image']  # 只返回图片字段


class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact
        fields = ['type', 'number']


class PostSerializer(serializers.ModelSerializer):
    contact = ContactSerializer(read_only=True)
    is_like = PostLikeSerializer(many=True, read_only=True, source='like')
    images = PostImageSerializer(many=True, read_only=True)  # 嵌套序列化器
    # student_name = serializers.CharField(source='student.name', read_only=True)
    school_name = serializers.CharField(source='school.name', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    comment_count = serializers.SerializerMethodField()  # 添加自定义字段
    identity = serializers.CharField(source='student.identity', read_only=True)
    nickname = serializers.CharField(source='student.nickname', read_only=True)
    avatar = serializers.CharField(source='student.image', read_only=True)

    # type = serializers.CharField(source='Contact.type', read_only=True, required=False)
    # number = serializers.CharField(source='Contact.number', read_only=True, required=False)

    class Meta:
        model = Post
        fields = '__all__'

    def get_comment_count(self, obj):
        return obj.comments_on_post.count()  # 使用 related_name 获取评论数量

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if 'is_like' not in representation:
            representation['is_like'] = []
        return representation


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'


# class ProductSerializer(serializers.ModelSerializer):
#     image = serializers.CharField(required=False)
#
#     class Meta:
#         model = Product
#         fields = '__all__'
class ProductImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = ['img']  # 只返回图片字段


class ProductSerializer(serializers.ModelSerializer):
    img = ProductImageSerializer(many=True, read_only=True)  # 嵌套序列化器
    seller = StudentSerializer(many=False, read_only=True)  # 修改 many=True 为 many=False
    #是根据字段名自动匹配方法的
    nickname = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = '__all__'

    def get_nickname(self, obj):
        return obj.seller.nickname if obj.seller else None


# class ProductImageSerializer(serializers.ModelSerializer):
#     img = serializers.CharField(required=False, default='')  # 设置 img 字段为空字符串
#
#     class Meta:
#         model = ProductImage
#         fields = ['img']  # 只返回图片字段
#
#
# class ProductSerializer(serializers.ModelSerializer):
#     img = ProductImageSerializer(many=True, read_only=True)  # 嵌套序列化器
#     #是根据字段名自动匹配方法的
#     nickname = serializers.SerializerMethodField()
#
#     class Meta:
#         model = Product
#         fields = '__all__'
#
#     def get_nickname(self, obj):
#         return obj.seller.nickname if obj.seller else None


"""之后如果有外键一定要按照下面的的方法处理，这样前端就只用传id就可以代表主键了，要不然要传实例也就是完整对象，而且不用写_id后缀"""


# class ProductSerializer(serializers.ModelSerializer):
#     seller = serializers.PrimaryKeyRelatedField(queryset=Student.objects.all())
#     school = serializers.PrimaryKeyRelatedField(queryset=School.objects.all())
#
#     class Meta:
#         model = Product
#         fields = ['id', 'seller', 'school', 'name', 'price', 'description', 'adress', 'aut', 'created_at', 'publisher', 'stock_quantity', 'category']


class CartItemSerializer(serializers.ModelSerializer):
    product = ProductSerializer(many=False, read_only=True)

    class Meta:
        model = CartItem
        fields = '__all__'


class OrderItemSerializer(serializers.ModelSerializer):
    product = ProductSerializer(many=False, read_only=True)

    class Meta:
        model = OrderItem
        fields = '__all__'


class OrderSerializer(serializers.ModelSerializer):
    n_name = serializers.CharField(source='buyer.nickname', read_only=True)
    order_items = OrderItemSerializer(many=True, source='orderitem_set', read_only=True)  # 使用 source 指定反向关系

    class Meta:
        model = Order
        fields = '__all__'


class ChatMessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatMessage
        fields = ['message', 'timestamp', 'sender', 'receiver']


class ReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = Report
        fields = '__all__'


class NotificationSerializer(serializers.ModelSerializer):
    # student_name = serializers.PrimaryKeyRelatedField(queryset=Student.objects.all())
    product = ProductSerializer(many=False, read_only=True)

    class Meta:
        model = Notification
        fields = '__all__'
